package com.qq.mobilemanager.activity;

import java.util.ArrayList;
import java.util.List;

import net.youmi.android.listener.Interface_ActivityListener;
import net.youmi.android.offers.OffersManager;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qq.mobilesafe.R;
import com.qq.mobilesafe.base.adapter.ViewHolder;
import com.qq.mobilesafe.base.adapter.recyclerview.CommonAdapter;
import com.qq.mobilesafe.base.adapter.recyclerview.OnItemClickListener;
import com.qq.mobilesafe.dialog.NiftyDialogBuilder;
import com.qq.mobilesafe.dialog.effects.SlideTop;
import com.qq.mobilesafe.domain.MainInfo;
import com.qq.mobilesafe.recyclerview.divider.HorizontalDividerItemDecoration;
import com.qq.mobilesafe.recyclerview.divider.VerticalDividerItemDecoration;
import com.qq.mobilesafe.utils.MD5Utils;
import com.qq.mobilesafe.utils.SharedPreferencesUtils;
import com.qq.mobilesafe.utils.UIUtil;
import com.qq.mobilesafe.view.StatusBarCompat;
import com.qq.mobilesafe.view.shimmer.Shimmer;
import com.qq.mobilesafe.view.shimmer.ShimmerTextView;

public class HomeActivity extends Activity {

	@ViewInject(R.id.tv_heimatitle)
	private ShimmerTextView shimmerTextView;

	@ViewInject(R.id.icon)
	private ImageView iv_logo;

	private String[] itemname;
	private String[] detail;
	private int[] picture;

	private List<MainInfo> infos;

	@ViewInject(R.id.rv_home)
	private RecyclerView recyclerView;
	private HomeAdapter adapter;
	private Shimmer shimmer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		initView();
		// sp = getSharedPreferences("config", MODE_PRIVATE);
	}

	private void initView() {
		StatusBarCompat.compat(this);
		// if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
		// getWindow().addFlags(
		// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// getWindow().addFlags(
		// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		// }
		setContentView(R.layout.activity_home);
		ViewUtils.inject(this);

		setAdapter();
		initListener();

		ObjectAnimator animator = ObjectAnimator.ofFloat(iv_logo, "rotationY",
				0, 90, 270, 360);
		animator.setDuration(3000);
		animator.setRepeatCount(animator.INFINITE);
		animator.start();
		if (shimmer != null && shimmer.isAnimating()) {
			shimmer.cancel();
		} else {
			shimmer = new Shimmer();
			shimmer.start(shimmerTextView);
		}
	}

	private void setAdapter() {
		adapter = new HomeAdapter(this, R.layout.item_main, infos);
		GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
		recyclerView.setLayoutManager(layoutManager);
		recyclerView
				.addItemDecoration(new HorizontalDividerItemDecoration.Builder(
						this).build());
		recyclerView
				.addItemDecoration(new VerticalDividerItemDecoration.Builder(
						this).color(Color.rgb(224, 224, 224)).build());
		recyclerView.setAdapter(adapter);
		// recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
	}

	private void initListener() {
		adapter.setOnItemClickListener(new OnItemClickListener<MainInfo>() {

			@Override
			public void onItemClick(ViewGroup parent, View view, MainInfo t,
					int position) {
				switch (position) {
				case 0:// 手机防盗
					showPasswordDialog();
					break;
				case 1:
					startActivity(FirewallActivity.class);
					break;
				case 2:// 软件管家
					startActivity(AppManagerActivity.class);
					break;
				case 3:// 进程管理
					startActivity(TaskManagerActivity.class);
					break;
				case 4:// 流量统计
					startActivity(TrafficStatsActivity.class);
					break;

				case 5:// 手机杀毒

					startActivity(AntivirusActivity.class);
					break;
				case 6:// 缓存清理

					startActivity(CleanCacheActivity.class);
					break;

				case 7:// 高级工具
					startActivity(AToolActivity.class);

					break;

				case 8:// 设置中心
					startActivity(SettingActivity.class);

					break;
				case 9:// 应用商店
						// 调用方式一：直接打开全屏积分墙
						// OffersManager.getInstance(HomeActivity.this).showOffersWall();

					// 调用方式二：直接打开全屏积分墙，并且监听积分墙退出的事件onDestory
					OffersManager.getInstance(HomeActivity.this)
							.showOffersWall(new Interface_ActivityListener() {

								/**
								 * 当积分墙销毁的时候，即积分墙的Activity调用了onDestory的时候回调
								 */
								@Override
								public void onActivityDestroy(Context context) {
									// Toast.makeText(context, "全屏积分墙退出了",
									// Toast.LENGTH_SHORT).show();
									OffersManager
											.getInstance(HomeActivity.this)
											.onAppExit();
								}
							});

					break;

				}

			}

			@Override
			public boolean onItemLongClick(ViewGroup parent, View view,
					MainInfo t, int position) {
				return false;
			}
		});

	}

	private void startActivity(Class<?> clazz) {
		Intent intent = new Intent(this, clazz);
		startActivity(intent);
	}

	/**
	 * 显示弹窗密码
	 */
	protected void showPasswordDialog() {
		String password = SharedPreferencesUtils.getString(HomeActivity.this,
				"password", null);
		if (!TextUtils.isEmpty(password)) {
			showPasswordInputDialog();
		} else {
			showPasswordSetDialog();
		}

	}

	private void showPasswordInputDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final AlertDialog dialog = builder.create();
		View view = View.inflate(this, R.layout.dialog_input_password, null);
		dialog.setView(view, 0, 0, 0, 0);

		final EditText et_password = (EditText) view
				.findViewById(R.id.et_password);
		Button bt_ok = (Button) view.findViewById(R.id.bt_ok);
		Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

		bt_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String password = et_password.getText().toString().trim();
				if (!TextUtils.isEmpty(password)) {
					String savedpass = SharedPreferencesUtils.getString(
							HomeActivity.this, "password", null);
					if (MD5Utils.encode(password).equals(savedpass)) {
						dialog.dismiss();

						startActivity(new Intent(HomeActivity.this,
								LostFindActivity.class));
					} else {
						Toast.makeText(HomeActivity.this, "密码错误",
								Toast.LENGTH_SHORT).show();
					}

				} else {
					Toast.makeText(HomeActivity.this, "输入内容不能为空",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		bt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

	/**
	 * 设置密码弹窗
	 */
	private void showPasswordSetDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final AlertDialog dialog = builder.create();

		View view = View.inflate(this, R.layout.dialog_set_password, null);

		dialog.setView(view, 0, 0, 0, 0);

		final EditText etpass = (EditText) view.findViewById(R.id.etpassword);
		final EditText etpass2 = (EditText) view.findViewById(R.id.etpassword2);

		Button btok = (Button) view.findViewById(R.id.btok);
		Button btcancel = (Button) view.findViewById(R.id.btcancel);

		btok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String pass = etpass.getText().toString().trim();
				String pass2 = etpass2.getText().toString().trim();
				if (!TextUtils.isEmpty(pass) && !pass2.isEmpty()) {
					if (pass.equals(pass2)) {
						SharedPreferencesUtils.saveString(HomeActivity.this,
								"password", MD5Utils.encode(pass));
						dialog.dismiss();
						startActivity(new Intent(HomeActivity.this,
								LostFindActivity.class));
					} else {
						Toast.makeText(HomeActivity.this, "两次密码不一致",
								Toast.LENGTH_SHORT).show();

					}
				} else {
					Toast.makeText(HomeActivity.this, "密码不能为空",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		btcancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

	@Override
	protected void onStart() {
		super.onStart();
		// 动画
		LayoutAnimationController animationController = new LayoutAnimationController(
				AnimationUtils.loadAnimation(this, R.anim.main_item));
		animationController.setOrder(LayoutAnimationController.ORDER_RANDOM);
		recyclerView.setLayoutAnimation(animationController);
		recyclerView.startLayoutAnimation();
	}

	private void initData() {
		itemname = UIUtil.getStringArray(R.array.itemname);
		detail = UIUtil.getStringArray(R.array.detail);
		picture = new int[] { R.drawable.home_safe,
				R.drawable.home_callmsgsafe, R.drawable.home_apps,
				R.drawable.home_taskmanager, R.drawable.home_netmanager,
				R.drawable.home_trojan, R.drawable.home_sysoptimize,
				R.drawable.home_tools, R.drawable.home_settings,
				R.drawable.app_store };

		infos = new ArrayList<MainInfo>();
		for (int i = 0; i < itemname.length; i++) {
			MainInfo maininfo = new MainInfo();
			maininfo.icon = picture[i];
			maininfo.title = itemname[i];
			maininfo.detail = detail[i];
			infos.add(maininfo);
		}
	}

	// 监听返回键
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// setIcon(R.drawable.mi)
			// new AlertDialog.Builder(this)
			// .setTitle("提示")
			// .setMessage("确认退出手机管家吗？")
			// .setPositiveButton("确定",
			// new DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(DialogInterface dialog,
			// int which) {
			// // Application app = getApplication();
			// // List<Activity> lists = app.get;
			// // for (Activity activity : lists) {
			// // activity.finish();
			// finish();
			// // 杀死自己
			// android.os.Process
			// .killProcess(android.os.Process
			// .myPid());
			//
			// }
			// })
			// .setNegativeButton("取消",
			// new DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(DialogInterface dialog,
			// int which) {
			// dialog.cancel();
			//
			// }
			// }).show();
			final NiftyDialogBuilder dialog = NiftyDialogBuilder
					.getInstance(this);
			dialog.withTitle("提示")
			// .withTitle(null) no title
					.withTitleColor("#616161")
					// def
					.withDividerColor("#11000000")
					// def
					// .withMessage("确认退出手机管家吗？")
					// .withMessage(null) no Msg
					// .withMessageColor("#000000")
					// def
					// .withIcon(getResources().getDrawable(R.drawable.icon))
					.isCancelableOnTouchOutside(true) // def |
														// isCancelable(true)
					.withDuration(700) // def
					.withEffect(new SlideTop()) // def Effectstype.Slidetop
					.withButton1Text("确定") // def gone
					.withButton2Text("取消") // def gone
					.setCustomView(R.layout.custom_view, this) // .setCustomView(View
																// or
																// ResId,context)
					.setButton1Click(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// 有米广告
							OffersManager.getInstance(HomeActivity.this)
									.onAppExit();
							// dialog.dismiss();
							finish();
							// 杀死自己
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					}).setButton2Click(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					}).show();

		}
		return true;
	}

	private class HomeAdapter extends CommonAdapter<MainInfo> {

		public HomeAdapter(Context context, int layoutId, List<MainInfo> datas) {
			super(context, layoutId, datas);
		}

		@Override
		public void convert(ViewHolder holder, MainInfo t) {
			holder.setText(R.id.tv_detail, t.detail);
			holder.setText(R.id.tv_title, t.title);
			holder.setImageResource(R.id.iv_icon, t.icon);
		}

	}
}
